#!/usr/bin/env bash

# Test GitHub backend URL tracking functionality
export MISE_LOCKFILE=1
export MISE_EXPERIMENTAL=1

# Clean up any existing installations
mise uninstall github:jdx/mise-test-fixtures 2>/dev/null || true

# Create initial configuration
cat <<EOF >mise.toml
[tools]
"github:jdx/mise-test-fixtures" = { version = "1.0.0", asset_pattern = "hello-world-1.0.0.tar.gz", bin_path = "hello-world-1.0.0/bin", postinstall = "chmod +x \$MISE_TOOL_INSTALL_PATH/hello-world-1.0.0/bin/hello-world" }
EOF

# Create lockfile
touch mise.lock

# First install - should fetch URL from GitHub API
echo "=== First install - fetching URL from GitHub API ==="
mise install
assert_contains "mise x -- hello-world" "hello world"

# Verify URL is stored in lockfile
echo "=== Verifying URL is stored in lockfile ==="
assert_contains "cat mise.lock" '[tools."github:jdx/mise-test-fixtures"]'
assert_contains "cat mise.lock" 'version = "1.0.0"'
assert_contains "cat mise.lock" 'backend = "github:jdx/mise-test-fixtures[asset_pattern=hello-world-1.0.0.tar.gz,bin_path=hello-world-1.0.0/bin]"'
# Get the current platform key
PLATFORM_KEY=$(mise x --cd . -- bash -c "echo \"\$(uname -s | tr '[:upper:]' '[:lower:]' | sed 's/darwin/macos/')-\$(uname -m | sed 's/x86_64/x64/' | sed 's/aarch64/arm64/')\"")
assert_contains "cat mise.lock" "[tools.\"github:jdx/mise-test-fixtures\".platforms.$PLATFORM_KEY]"
assert_contains "cat mise.lock" 'name = "hello-world-1.0.0.tar.gz"'
assert_contains "cat mise.lock" 'url = "https://github.com/jdx/mise-test-fixtures/releases/download/v1.0.0/hello-world-1.0.0.tar.gz"'
assert_contains "cat mise.lock" 'url_api = "https://api.github.com/repos/jdx/mise-test-fixtures/releases/assets/272317030"'

echo "Lockfile after installation:"
cat mise.lock

# Uninstall and reinstall - should reuse URL from lockfile
echo "=== Uninstall and reinstall - should reuse cached URL ==="
mise uninstall "github:jdx/mise-test-fixtures@1.0.0"
mise install

# Should still work with cached URL
assert_contains "mise x -- hello-world" "hello world"

echo "Test completed successfully!"
